package com.d2.modules.system.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.d2.modules.system.category.entity.Category;
import com.d2.modules.system.category.mapper.ICategoryMapper;
import com.d2.modules.system.category.service.ICategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.function.Consumer;

/**
 * @author mayihua
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<ICategoryMapper, Category> implements ICategoryService {

    @Override
    public List<Category> tree(Long id) {
        Category q = new Category();
        q.setPid(id);
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>(q);
        List<Category> list = this.list(queryWrapper);
        buildTree(list);
        return list;
    }

    @Override
    public List<Category> children(Long id) {
        Category category = this.getById(id);
        Category q = new Category();
        q.setPid(category.getId());
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>(q);
        List<Category> list = this.list(queryWrapper);
        buildTree(list);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Category delById(Long id) {
        Category category = this.getById(id);
        if(category != null){
            this.removeById(id);
            Category query = new Category();
            query.setPid(category.getId());
            List<Category> children = this.list(new QueryWrapper<>(query));
            children.forEach(category1 -> deleteById(category1.getId()));
            return category;
        }
        return null;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        Category category = delById(id);
        if(category != null){
            Long pid = category.getPid();
            updateHasChildren(pid);
        }
    }

    @Override
    public void updateHasChildren(Long pid) {
        Category q = new Category();
        q.setPid(pid);
        int count = this.count(new QueryWrapper<>(q));
        if(count == 0){
            Category update = new Category();
            update.setId(pid);
            update.setHasChildren(0);
            this.updateById(update);
        }
    }


    private void buildTree(List<Category> list) {
        for (Category c : list) {
            Category query = new Category();
            query.setPid(c.getId());
            QueryWrapper<Category> qw = new QueryWrapper<>(query);
            List<Category> list1 = this.list(qw);
            this.buildTree(list1);
            c.setChildren(list1);
        }
    }
}
